<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域视图 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addUser">添加用户</el-button></el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table
        :data="userTableData" border  style="width: 100%">
        <el-table-column  label="#" width="180" type="index"> </el-table-column>
        <el-table-column  prop="username" label="姓名"> </el-table-column>
        <el-table-column  prop="email" label="邮箱"> </el-table-column>
        <el-table-column  prop="mobile" label="电话"> </el-table-column>
        <el-table-column  prop="role_name" label="角色"> </el-table-column>
        <el-table-column  prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"
            active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editUserInfo(scope.row.id)" ></el-button>
            <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteUserInfo(scope.row.id)" ></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
              <el-button  size="mini"  type="warning"  icon="el-icon-setting" @click="allotRoles(scope.row)" ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 修改用户对话框 -->
      <el-dialog
          title="修改用户"
          :visible.sync="editUserDialogVisible"
          width="50%" @close="editDialogClosed">
          <el-form ref="editUserFormRef" :model="eidtUserForm" label-width="80px" :rules="editUserFormRules">
            <el-form-item label="用户名"  prop="username">
              <el-input v-model="eidtUserForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱"  prop="email">
              <el-input v-model="eidtUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号"  prop="mobile">
              <el-input v-model="eidtUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditUser">确 定</el-button>
          </span>
      </el-dialog>
      <!-- 添加用户对话框 -->
      <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="50%" @close="addDialogClosed">
          <el-form ref="addUserFormRef" :model="addUserForm" label-width="80px" :rules="addUserFormRules">
            <el-form-item label="用户名"  prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码"  prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱"  prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号"  prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddUser">确 定</el-button>
          </span>
      </el-dialog>
      <!-- 添加用户对话框 -->
      <el-dialog
          title="分配角色"
          :visible.sync="allotRolesDialogVisible"
          width="50%" @close="setRoleDialogClosed">
          <el-form ref="allotRolesFormRef" :model="allotRolesForm" label-width="100px">
            <el-form-item label="当前的用户">
              <el-input v-model="allotRolesForm.username"></el-input>
            </el-form-item>
            <el-form-item label="当前的角色">
              <el-input v-model="allotRolesForm.role_name"></el-input>
            </el-form-item>
            <el-form-item label="分配新角色">
              <el-select v-model="selectedRoleId" placeholder="请选择角色">
                <el-option v-for="item in rolesList" :key="item.id" :value="item.id" :label="item.roleName"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="allotRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAllotRoles">确 定</el-button>
          </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义校验规则
    var validateMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    var validateEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    return {
      // 用户列表数据
      userTableData: [],
      // 得到用户列表的
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      total: 0,
      // 添加用户对话框
      addUserDialogVisible: false,
      // 新增用户对话框form
      addUserForm: {},
      // 修改用户对话框
      editUserDialogVisible: false,
      // 修改用户对话框form
      eidtUserForm: {},
      // 添加用户表单的验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请选择用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      // 修改用户表单的验证规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      // 分配角色对话框
      allotRolesDialogVisible: false,
      // 角色列表
      rolesList: [],
      // 当前角色下的用户信息
      allotRolesForm: {},
      // 选中的角色id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserData()
  },
  methods: {
    // 获取用户数据
    async getUserData () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      this.userTableData = res.data.users
      this.total = res.data.total
    },
    // 改变用户状态
    async changeUserState (row) {
      // 这边发送过去，服务器的后台数据库自己会进行改变的
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        this.$message.error('用户状态更新失败')
      } else {
        this.$message.success('用户状态更新成功')
      }
    },
    // 编辑用户信息
    async editUserInfo (id) {
    // 修改用户对话框关闭进行的操作
      const { data: res } = await this.$http.get(`users/${id}`)
      console.log(res)
      if (res.meta.status === 200) {
        this.eidtUserForm = res.data
        this.editUserDialogVisible = true
      } else {
        this.$message.error('查询失败')
      }
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserData()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserData()
    },
    // 实现搜索功能
    searchData () {
      this.getUserData()
    },
    // 修改用户对话框关闭进行的操作
    editDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 添加用户对话框
    addUser () {
      this.addUserDialogVisible = true
    },
    // 新增用户
    submitAddUser () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          console.log(res)
          if (res.meta.status === 201) {
            this.$message.success('添加成功')
            this.addUserDialogVisible = false
            this.getUserData()
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },
    // 监听新增用户对话框关闭
    addDialogClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 编辑用户对话框提交
    submitEditUser () {
      this.$refs.editUserFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${this.eidtUserForm.id}`, {
            email: this.eidtUserForm.email,
            mobile: this.eidtUserForm.mobile
          })
          // console.log(res)
          if (res.meta.status === 200) {
            this.$message.success('修改成功')
            this.editUserDialogVisible = false
            this.getUserData()
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },
    // 删除用户
    deleteUserInfo (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        } else {
          this.$message.success('删除用户成功')
          this.getUserData()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 分配角色对话框的显示
    async allotRoles (row) {
      this.allotRolesForm = row
      this.allotRolesDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      } else {
        console.log(res)
        this.rolesList = res.data
      }
    },
    // 点击确定，分配角色
    async submitAllotRoles () {
      const { data: res } = await this.$http.put(`users/${this.allotRolesForm.id}/role`, {
        rid: this.selectedRoleId
      })
      console.log(res)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.getUserData()
        this.allotRolesDialogVisible = false
      } else {
        this.$message.error('设置角色失败')
      }
    },
    // 监听分配角色对话框的关闭，清空对话框里面的数据
    setRoleDialogClosed () {
      this.allotRolesForm = {}
      this.selectedRoleId = ''
    }
  }
}
</script>

<style scoped>
.el-row{
    margin-bottom: 15px
}
</style>
